package hot100;

import java.util.Arrays;

public class Solution1049 {
    public int lastStoneWeightII(int[] stones) {
        int sum = 0;
        for (int i : stones) {
            sum += i;
        }
        int n = sum / 2;
        boolean[][] dp = new boolean[stones.length + 1][n + 1];
        dp[0][0] = true;
        for (int i = 0; i < stones.length; i++) {
            for (int j = 0; j <= sum; j++) {
                if (j < stones[i]) {
                    dp[i + 1][j] = dp[i][j];
                } else {
                    dp[i + 1][j] = dp[i][j] ||  dp[i][j - stones[i]];
                }
            }
        }
        int neg = 0;
        for (int j = 0; j <= n; j++) {
            if (dp[stones.length - 1][j]) {
                neg = j;
            }
        }
        return sum - 2 * neg;
    }

    public int lastStoneWeight(int[] stones) {
        int sum = 0;
        for (int i = 0; i < stones.length; i++) {
            sum += stones[i];
        }
        int n = sum / 2;
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;
        for (int i = 0; i < stones.length; i++) {
            for (int j = n; j >= stones[i]; j--) {
                dp[j] = dp[j - stones[i]];
            }
        }
        int neg = 0;
        for (int i = n; i >= 0; i--) {
            if (dp[i]) {
                neg = i;
                break;
            }
        }
        return sum - 2 * neg;
    }
}
